package com.cuanbobox.utils;

import android.view.MotionEvent;
import android.view.View;
import com.cuanbobox.bean.EventBusBean;
import com.cuanbobox.uart.Uart;
import org.greenrobot.eventbus.EventBus;

public class TouchHelper implements View.OnTouchListener {
    public static final byte EVENT_DOWN = 1;
    public static final byte EVENT_UP = 2;
    public static final byte EVENT_MOVE = 3;
    private Uart uart;
    private float inHdmiWidth=1920;
    private float inHdmiHeight=1080;

    public TouchHelper(View v){
        v.setOnTouchListener(this);
        uart = Uart.createUart(new Uart.Callback() {
            @Override
            public void onUartReceived(byte[] data, int length) {
                if (uart != null && data != null) {
                    uart.send( data );
                }
            }
        }, Uart.PATH_TOUCH, 115200);
        if (uart != null) {
            uart.open();
        }
    }

    protected byte[] getTouchData( byte event, byte id, int x, int y) {
        int index = 0;
        byte[] buf = new byte[17];

        buf[index] = (byte) 0x55;
        index++;

        buf[index] = (byte) 0xFE;
        index++;

        buf[index] = event;
        index++;

        buf[index] = id;
        index++;

        index += intTobyteArray( buf, index, 2 );
        index += intTobyteArray( buf, index, x );
        index += intTobyteArray( buf, index, y );

        buf[index] = 0x0A;
        index++;

        return buf;
    }

    public int intTobyteArray(byte[] b, int offset, int val) {
        b[offset] = (byte) ((val >> 24) & 0xFF);
        b[offset + 1] = (byte) ((val >> 16) & 0xFF);
        b[offset + 2] = (byte) ((val >> 8) & 0xFF);
        b[offset + 3] = (byte) (val & 0xFF);
        return 4;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int id = event.getPointerId( event.getActionIndex() );
        float unitX=inHdmiWidth/DensityUtil.getScreenWidth(v.getContext());
        float unitY=inHdmiHeight/DensityUtil.getScreenHeigth(v.getContext());
        int x=(int)(event.getX()*unitX);
        int y=(int)(event.getY()*unitY);
        if(event.getAction()==MotionEvent.ACTION_DOWN){
            EventBus.getDefault().post(new EventBusBean(EventBusBean.DRAWBOARD_TOUCH));
            uart.send(getTouchData(EVENT_DOWN,(byte)id,x,y));
        }else if(event.getAction()==MotionEvent.ACTION_UP){
            uart.send(getTouchData(EVENT_UP,(byte)id,x,y));
        }else if(event.getAction()==MotionEvent.ACTION_MOVE){
            uart.send(getTouchData(EVENT_MOVE,(byte)id,x,y));
        }
        return true;
    }

    public void close(){
        if (uart != null) {
            uart.close();
        }
    }
}
